package com.china08.yxyapi.service.manage.tec.teaching.homework.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.china08.yxyapi.entity.db.res.YxyResBookContentsKnoledges;
import com.china08.yxyapi.entity.es.ElasticYxyYxyQuesResource;
import com.china08.yxyapi.entity.mg.homework.HomeWorkQuesUsed;
import com.china08.yxyapi.entity.mg.homework.HomeworkQuesFavorite;
import com.china08.yxyapi.repository.db.YxyResBookContentsKnoledgesRepository;
import com.china08.yxyapi.repository.es.ElasticYxyYxyQuesResourceRespository;
import com.china08.yxyapi.repository.mg.homework.HomeworkQuesFavoriteRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkQuesUsedRepository;
import com.china08.yxyapi.service.manage.tec.teaching.homework.ElasticQuesService;
import com.china08.yxyapi.service.manage.tec.teaching.homework.HomeworkQuestionService2;
import com.china08.yxyapi.util.YxyResUtil;

@Service
public class HomeworkQuestionServiceImpl2 implements HomeworkQuestionService2 {

    @Autowired
    private ElasticQuesService elasticQuesService;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private ElasticYxyYxyQuesResourceRespository elasticYxyYxyQuesResourceRespository;

    @Autowired
    private HomeworkQuesFavoriteRepository homeworkQuesFavoriteRepository;

    @Autowired
    private HomeworkQuesUsedRepository homeWorkQuesUsedRepository;

    @Autowired
    private YxyResBookContentsKnoledgesRepository yxyResBookContentsKnoledgesRepository;

    @Autowired
    private YxyResUtil yxyResUtil;

    /**
     * 封装基本查询
     * 
     * @param boolQueryBuilder
     * @param level
     * @param type
     * @param use
     * @return
     */
    @Override
    public BoolQueryBuilder get(BoolQueryBuilder boolQueryBuilder, String level, String type, String use) {
        if (StringUtils.isNotBlank(level) && !StringUtils.equals("all", level)) {
            TermQueryBuilder builder = new TermQueryBuilder("difficultyLevel", level);
            boolQueryBuilder.must(builder);
        }
        if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            TermQueryBuilder builder = new TermQueryBuilder("questionType", type);
            boolQueryBuilder.must(builder);
        } else {
            // 目前只有 单选 和多选
            BoolQueryBuilder typeOr = new BoolQueryBuilder();
            TermQueryBuilder builder1 = new TermQueryBuilder("questionType", "1");
            TermQueryBuilder builder8 = new TermQueryBuilder("questionType", "8");
            typeOr.should(builder1);
            typeOr.should(builder8);
            boolQueryBuilder.must(typeOr);
        }
        if (StringUtils.isNotBlank(use) && !StringUtils.equals("all", use)) {
            List<String> ids = new ArrayList<String>();
            if (StringUtils.equals("0", use)) {
                // 未使用过
            } else {
                // 使用过
            }
        }
        return boolQueryBuilder;
    }

    /**
     * 查询page
     * 
     * @param boolQueryBuilder
     * @param pageable
     * @return
     */
    private Page<ElasticYxyYxyQuesResource> getPage(BoolQueryBuilder boolQueryBuilder, Pageable pageable) {
        SearchQuery query = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(boolQueryBuilder).build();
        Page<ElasticYxyYxyQuesResource> page = elasticsearchTemplate.queryForPage(query,
                ElasticYxyYxyQuesResource.class);
        return page;
    }

    @Override
    public boolean checkCollectionQuestion(String userId, String quesId) {
        long count = homeworkQuesFavoriteRepository.countByTeacherIdAndQuesId(userId, quesId);
        return count > 0;
    }

    @Override
    public Page<ElasticYxyYxyQuesResource> collectionfindByMy(String phase, String subject, String userId, String level,
            String type, Pageable pageable) {

        Page<HomeworkQuesFavorite> favoritePage = null;
        if (StringUtils.isNotBlank(level) && !StringUtils.equals("all", level) && StringUtils.isNotBlank(type)
                && !StringUtils.equals("all", type)) {
            favoritePage = homeworkQuesFavoriteRepository
                    .findByTeacherIdAndStageAndSubjectAndDifficultyLevelAndQuesType(userId, phase, subject,
                            Integer.parseInt(level), type, pageable);
        } else if (StringUtils.isNotBlank(level) && !StringUtils.equals("all", level)) {
            favoritePage = homeworkQuesFavoriteRepository.findByTeacherIdAndStageAndSubjectAndDifficultyLevel(userId,
                    phase, subject, Integer.parseInt(level), pageable);
        } else if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            favoritePage = homeworkQuesFavoriteRepository.findByTeacherIdAndStageAndSubjectAndQuesType(userId, phase,
                    subject, type, pageable);
        } else {
            favoritePage = homeworkQuesFavoriteRepository.findByTeacherIdAndStageAndSubject(userId, phase, subject,
                    pageable);
        }
        List<String> quesIds = favoritePage.getContent().stream().map(x -> x.getQuesId()).collect(Collectors.toList());

        Page<ElasticYxyYxyQuesResource> page = null;
        if (quesIds.size() > 0) {
            BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
            TermsQueryBuilder builder = new TermsQueryBuilder("id", quesIds);
            boolQueryBuilder.must(builder);
            page = getPage(boolQueryBuilder, pageable);
        } else {
            List<ElasticYxyYxyQuesResource> list = new ArrayList<ElasticYxyYxyQuesResource>();
            page = new PageImpl<ElasticYxyYxyQuesResource>(list, pageable, 0);
        }
        return page;
    }

    @Override
    public void collectionQuestion(String userId, String schoolId, String quesId) {
        ElasticYxyYxyQuesResource elasticYxyYxyQuesResource = elasticYxyYxyQuesResourceRespository.findById(quesId);
        Assert.notNull(elasticYxyYxyQuesResource, "试题不存在请刷新页面");
        HomeworkQuesFavorite favorite = homeworkQuesFavoriteRepository.findByQuesIdAndTeacherId(quesId, userId);
        Assert.isNull(favorite, "您已经收藏过了，请刷新页面");
        favorite = new HomeworkQuesFavorite();
        favorite.setCreatedBy(userId);
        favorite.setLastModifiedBy(userId);
        favorite.setTeacherId(userId);
        favorite.setSchoolId(schoolId);
        favorite.setStage(elasticYxyYxyQuesResource.getPhase());
        favorite.setSubject(elasticYxyYxyQuesResource.getSubject());
        favorite.setQuesId(elasticYxyYxyQuesResource.getId());
        List<Integer> knowIds = elasticYxyYxyQuesResource.getKnowledgeIds();
        String know = "";
        if (knowIds != null && knowIds.size() > 0) {
            know = StringUtils.join(knowIds, ",");
        }
        favorite.setKnowIds(know);
        favorite.setQuesType(elasticYxyYxyQuesResource.getQuestionType());
        favorite.setDifficultyLevel(Integer.parseInt(elasticYxyYxyQuesResource.getDifficultyLevel()));
        homeworkQuesFavoriteRepository.save(favorite);
    }

    @Override
    public void collectionRemoveQuestion(String userId, String quesId) {
        HomeworkQuesFavorite favorite = homeworkQuesFavoriteRepository.findByQuesIdAndTeacherId(quesId, userId);
        Assert.notNull(favorite, "您并没有收藏试题，请刷新页面");
        homeworkQuesFavoriteRepository.delete(favorite);
    }

    @Override
    public Long countQuestionUse(String quesId) {
        HomeWorkQuesUsed homeWorkQuesUsed = homeWorkQuesUsedRepository.findByQuesId(quesId);
        return homeWorkQuesUsed != null ? homeWorkQuesUsed.getUsedCount() : 0;
    }

    @Override
    public double questionDateTime(String quesId) {
        ElasticYxyYxyQuesResource elasticYxyYxyQuesResource = elasticQuesService.findByEsQuesId(quesId);
        Assert.notNull(elasticYxyYxyQuesResource, "资源未找到请刷新页面");
        String quesType = elasticYxyYxyQuesResource.getQuestionType();
        String queslevel = elasticYxyYxyQuesResource.getDifficultyLevel();
        double dateTime = 0.0;
        // 简单
        if (StringUtils.equals("1", queslevel)) {
            // 单选
            if (StringUtils.equals("1", quesType)) {
                dateTime = 1;
            }
            // 多选
            else if (StringUtils.equals("8", quesType)) {
                dateTime = 1.5;
            }
        }
        // 中等
        else if (StringUtils.equals("2", queslevel)) {
            // 单选
            if (StringUtils.equals("1", quesType)) {
                dateTime = 2;
            }
            // 多选
            else if (StringUtils.equals("8", quesType)) {
                dateTime = 2.5;
            }
        }
        // 困难
        else if (StringUtils.equals("3", queslevel)) {
            // 单选
            if (StringUtils.equals("1", quesType)) {
                dateTime = 4;
            }
            // 多选
            else if (StringUtils.equals("8", quesType)) {
                dateTime = 4.5;
            }
        }
        return dateTime;
    }

    @Override
    public Page<ElasticYxyYxyQuesResource> questionFindByBookcontentAndLevelAndTypeAndUse(String bookcontent,
            String level, String type, String use, String userId, Pageable pageable) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 基本查询
        // boolQueryBuilder = get(boolQueryBuilder, level, type, use);
        // // 目录
        // if (StringUtils.isNotBlank(bookcontent) && !StringUtils.equals("all",
        // bookcontent)) {
        // // 目录查询
        // boolQueryBuilder = questionFindByBookcontent(boolQueryBuilder,
        // bookcontent);
        // }
        TermQueryBuilder builder = new TermQueryBuilder("phase", "02");
        boolQueryBuilder.must(builder);
        TermQueryBuilder builder1 = new TermQueryBuilder("subject", "jcsub11");
        boolQueryBuilder.must(builder1);
        // TermQueryBuilder builder2 = new TermQueryBuilder("questionType",
        // "2");
        // boolQueryBuilder.must(builder2);
        Page<ElasticYxyYxyQuesResource> page = getPage(boolQueryBuilder, pageable);
        return page;
    }

    @Override
    public Page<ElasticYxyYxyQuesResource> questionFindByKnowAndLevelAndTypeAndUse(String know, String level,
            String type, String use, String userId, Pageable pageable) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (StringUtils.isNotBlank(know) && !StringUtils.equals("all", know)) {
            TermQueryBuilder builder = new TermQueryBuilder("knowFullIds", Integer.parseInt(know));
            boolQueryBuilder.must(builder);
        }
        // 基本查询
        boolQueryBuilder = get(boolQueryBuilder, level, type, use);
        Page<ElasticYxyYxyQuesResource> page = getPage(boolQueryBuilder, pageable);
        return page;
    }

    @Override
    public Page<ElasticYxyYxyQuesResource> questionFindByMyGroupId(String userId, String groupId, String level,
            String type) {
        return null;
    }

    @Override
    public BoolQueryBuilder questionFindByBookcontent(BoolQueryBuilder boolQueryBuilder, String bookcontent) {
        // 找到这个目录下的所有子目录
        List<String> bookcontentList = yxyResUtil.findTocByTocParent(bookcontent);
        List<YxyResBookContentsKnoledges> bookContentsKnoledges = yxyResBookContentsKnoledgesRepository
                .findByBookContentIdIn(bookcontentList);
        if (bookContentsKnoledges.size() > 0) {
            List<Integer> knowIds = bookContentsKnoledges.stream().map(x -> x.getKnowledgeId())
                    .collect(Collectors.toList());
            TermsQueryBuilder builder = new TermsQueryBuilder("knowFullIds", knowIds);
            boolQueryBuilder.must(builder);
        } else {
            List<Integer> knoids = new ArrayList<Integer>();
            TermsQueryBuilder builder = new TermsQueryBuilder("knowFullIds", knoids);
            boolQueryBuilder.must(builder);
        }
        return boolQueryBuilder;
    }

}
